package cn.edu.seu.herald.informationplatform.dao.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import cn.edu.seu.herald.informationplatform.bean.auth.LeagueSession;

public class LeagueSessionDao extends DataAccessObject{
	private static LeagueSessionDao daoInstance=null;	
	//Constructor of LeagueDao
	protected LeagueSessionDao(){	
	}
	//Get LeagueDao instance
	public static LeagueSessionDao getDao(){
		if(daoInstance==null){
			daoInstance=new LeagueSessionDao();
		}
		return daoInstance;
	}
	
	public boolean contains(int id) throws SQLException {
		Connection con = getConnectionLeague();
		try {
			PreparedStatement ps = con.prepareStatement("select * from lg_league_session where id=?");
			ps.setInt(1,id);
			int count = 0;
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				count++;
			}
			if (count==0) {
				return false;
			}else {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		finally{
			closeCon(con);
		}
	}
	
	//get
	public LeagueSession getLeagueSessionById(int id)throws SQLException{
		Connection con = getConnectionLeague();
		LeagueSession ls = new LeagueSession();
		try {
			PreparedStatement ps = con.prepareStatement("select * from lg_league_session where id=?");
			ps.setInt(1,id);
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()){
				ls.setLeagueId(rs.getInt(2));
			    ls.setExpiredTime(rs.getLong(3));
			    ls.setLeagueIp(rs.getString(4));
			}
			closeRs(rs);
			return ls;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		finally{
			closeCon(con);
		}
	}
	
	//get leagueId from id
	public int getLeagueIdFromId(int id) throws SQLException{
		Connection con = getConnectionLeague();
		int leagueId = -1;
		try {
			PreparedStatement ps = con.prepareStatement("select league_id from lg_league_session where id=?");
			ps.setInt(1,id);
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()){
				leagueId = rs.getInt(1);
			}
			closeRs(rs);
			return leagueId;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		finally{
			closeCon(con);
		}
	}
	
	public void deleteLeagueSession(int id)throws SQLException{
		Connection con = getConnectionLeague();
		try {
			PreparedStatement ps = con.prepareStatement(
					"delete from lg_league_session where id=?");
			ps.setInt(1, id);
			ps.executeUpdate();
		} finally {
			con.close();
		}
	}
}
